package com.auth.manage.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import com.auth.manage.admin.domain.service.AdminService;
import com.auth.manage.admin.infr.exception.AdminErrorCode;
import com.auth.manage.admin.infr.exception.AdminException;
import com.auth.manage.admin.param.FreezeParam;
import com.auth.manage.base.responce.BaseResponce;
import com.auth.manage.base.responce.MultipleResponce;
import com.auth.manage.common.user.api.constant.UserRole;
import com.auth.manage.common.user.api.request.condition.UserQueryByUserIdCondition;
import com.auth.manage.common.user.api.responce.UserResponce;
import com.auth.manage.common.user.api.service.UserFacadeService;
import com.auth.manage.web.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.function.Consumer;

@RequestMapping("admin/user")
@RestController
@RequiredArgsConstructor
public class UserAdminController {
    private final AdminService orderService;
    private final UserFacadeService userFacadeService;
    // 冻结用户
    @PostMapping("freeze")
    public Result freeze(Long userId){
        // 1.校验当前用户是否存在且确实是管理员或OP
        // todo satoken判断过了还需不需要再次判断
        Long adminUserId = (Long) StpUtil.getLoginId();
        MultipleResponce<UserResponce> responce = userFacadeService.queryByCondition(new UserQueryByUserIdCondition(adminUserId));
        responce.getData().stream().findFirst().ifPresentOrElse(userResponce -> {
            if (!UserRole.ADMIN.name().equals(userResponce.getUserRole().name()) ||
                    !UserRole.OP.name().equals(userResponce.getUserRole().name()))
                throw new AdminException(AdminErrorCode.YOU_HAVE_NO_PERMISSION);
            // todo 这里需不需要做用户信息查询的校验？如果这里不校验，就留给UserService做校验；或Admin和User都做校验
        }, () ->{
            throw new AdminException(AdminErrorCode.ADMIN_OR_OP_NOT_EXIST);
        });
        // 2.冻结用户
        BaseResponce baseResponce = userFacadeService.freezeUserByUserId(userId);
        if (baseResponce.getSuccess()){
            // 3.更新用户Session信息
            refreshUserInSession(userId);
            return Result.success();
        }else {
            return Result.error(baseResponce.getResponceCode(), baseResponce.getResponceMessage());
        }
    }

    @PostMapping("unfreeze")
    public Result unfreeze(Long userId){
        // 1.判断当前操作人是不是Admin或OP
        long adminId = StpUtil.getLoginIdAsLong();
        MultipleResponce<UserResponce> responce = userFacadeService.queryByCondition(new UserQueryByUserIdCondition(adminId));
        responce.getData().stream().findFirst().ifPresentOrElse(userResponce -> {
            Assert.isTrue(UserRole.ADMIN.name().equals(userResponce.getUserRole().name()) || UserRole.OP.name().equals(userResponce.getUserRole().name()),()->new AdminException(AdminErrorCode.YOU_HAVE_NO_PERMISSION));
        },()->{
            throw new AdminException(AdminErrorCode.ADMIN_OR_OP_NOT_EXIST);
        });
        // 2.构建请求，让UserService修改用户状态
        // 3.返回结果
        BaseResponce baseResponce = userFacadeService.unfreezeUserByUserId(userId);
        if (baseResponce.getSuccess()) {
            // 更新用户Session
            refreshUserInSession(userId);
            return Result.success();
        }
        else
            return Result.error(baseResponce.getResponceCode(), baseResponce.getResponceMessage());
    }

    private void refreshUserInSession(Long userId) {
        // 重新查询用户信息放入Session
        UserQueryByUserIdCondition condition = new UserQueryByUserIdCondition(userId);
        MultipleResponce<UserResponce> responce = userFacadeService.queryByCondition(condition);
        UserResponce userResponce = responce.getData().stream().findFirst().get();
        StpUtil.getSession().set(String.valueOf(userId), userResponce);
    }


}
